package com.dreamsail.core.util;

import com.dreamsail.core.constant.ErrorMessage;
import com.dreamsail.core.model.system.BaseException;
import com.dreamsail.core.model.system.UserTokenInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class JwtUtil {
    private static final String secretKey = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1N12121212iJ9"; //进行数字签名的私钥，一定要保管好

    public static void main(String[] args) throws Exception {

        //获取系统的当前时间
    /*    long ttlMillis = System.currentTimeMillis();
        Date now = new Date(ttlMillis);*/

        //生成jwt令牌
       /* JwtBuilder jwtBuilder = Jwts.builder()
                .setId("66")//设置jwt编码
                .setSubject("程序员")//设置jwt主题
                .setIssuedAt(new Date())//设置jwt签发日期
                //.setExpiration(date)//设置jwt的过期时间
                .claim("t", "admin")
                .claim("company", "itheima")
                .signWith(SignatureAlgorithm.HS256, secretKey);
        //生成jwt
        String jwtToken = jwtBuilder.compact();
        System.out.println(jwtToken);*/
//        String s = acquireJWT("123456", "1", "123");
      /*  byte[] bytes = DatatypeConverter.parseBase64Binary(secretKey);
        //解析jwt,得到其内部的数据
        Claims claims = Jwts.parser().setSigningKey(bytes).parseClaimsJws(s).getBody();
        System.out.println(claims);
        Claims claims1 = parseJWT(s);
        System.out.println(claims1);*/
    }

    /**
     * 生成串
     *
     * @param id
     * @param account
     * @return
     * @throws Exception
     */
    public static String acquireJWT(String account, Long id) {
        //生成jwt令牌
        JwtBuilder jwtBuilder = Jwts.builder()
                .setId(UUIDUtil.getUUIDStr())//设置jwt
                .setSubject("token")//设置jwt主题
                .setIssuedAt(new Date())//设置jwt签发日期
                .setExpiration(new Date(System.currentTimeMillis() + 60 * 60 * 1000))//设置jwt的过期时间
                .claim("account", account)
                .claim("id", id)
//              .claim("company", "itheima")
                .signWith(SignatureAlgorithm.HS256, secretKey);
        return jwtBuilder.compact();
    }

    /**
     * 解析JWT字符串
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) {
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static UserTokenInfo parseUserInfo(String token, HttpServletResponse response) {
        UserTokenInfo userTokenInfo = new UserTokenInfo();
        Claims claims = parseJWT(token);

        Date expiration = claims.getExpiration();
        if (expiration.getTime() < System.currentTimeMillis()) {
            throw new BaseException(ErrorMessage.LOGIN_OUT);
        }
        userTokenInfo.setUserId(Long.valueOf(claims.get("id").toString()));
        userTokenInfo.setAccount(claims.get("account").toString());


        response.addHeader("Authorization", token);
        return userTokenInfo;
    }
}
 